﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using CloudShot.Editor.CanvasFigures;

namespace CloudShot.Utils
{
  internal static class ReflectionUtils
  {
    public static PropertyInfo GetPropertyInfo<TObject, TProperty>(this Expression<Func<TObject, TProperty>> expression)
    {
      Expression body = expression;
      if (body is LambdaExpression)
      {
        body = ((LambdaExpression)body).Body;
      }

      if (body.NodeType == ExpressionType.MemberAccess)
      {
        return ((MemberExpression)body).Member as PropertyInfo;
      }

      throw new ArgumentException("Invalid expression type");
    }

    public static TValue GetPropertyValue<TObject, TValue>(this Expression<Func<TObject, TValue>> expression, TObject obj) where TObject : CanvasObject
    {
      PropertyInfo propertyInfo = GetPropertyInfo(expression);
      return (TValue)propertyInfo.GetValue(obj);
    }

    public static void SetPropertyValue<TObject, TValue>(this Expression<Func<TObject, TValue>> expression, TObject obj, TValue value) where TObject : CanvasObject
    {
      PropertyInfo propertyInfo = expression.GetPropertyInfo();
      propertyInfo.SetValue(obj, value, null);
    }
  }
}
